package com.lieve;

import com.google.gson.Gson;
import com.lieve.entity.Blog;
import com.lieve.mapper.BlogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.util.Properties;

/**
 * @author sunlijiang
 * @date 2020/4/11
 */
@Slf4j
public class Main {

    public static void main(String[] args) {
        DataSourceFactory dataSourceFactory = new UnpooledDataSourceFactory();
        Properties jdbcProperites = new Properties();
        jdbcProperites.put("driver", "com.mysql.cj.jdbc.Driver");
        jdbcProperites.put("url", "jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false");
        jdbcProperites.put("username", "root");
        jdbcProperites.put("password", "mysql");
        dataSourceFactory.setProperties(jdbcProperites);
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("dev", transactionFactory, dataSourceFactory.getDataSource());
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(BlogMapper.class);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        /**
         * new Gson().toJson(dataSourceFactory.getDataSource()) =
         * {
         *     "driver": "com.mysql.cj.jdbc.Driver",
         *     "url": "jdbc:mysql://localhost:3306/db_test",
         *     "username": "root",
         *     "password": "mysql"
         * }
         */
        System.out.println(new Gson().toJson(dataSourceFactory.getDataSource()));
        Blog blog = sqlSession.selectOne("com.lieve.mapper.BlogMapper.getById", 1L);
        System.out.println(blog);
        try {
            sqlSession.update("com.lieve.mapper.BlogMapper.update", new Blog(1L, "title1", "content"));
            // int insert = sqlSession.insert("com.lieve.mapper.BlogMapper.save", new Blog(2L, "title2", "content2"));
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        }
        log.info("error");
        sqlSession.commit();
    }
}
